package ar.com.larctest.tasks;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import ar.com.larctest.R;
import ar.com.larctest.dbHelper.SQLLARCTESTHelper;
import ar.com.larctest.entities.Horses;
import ar.com.larctest.entities.HorsesRacing;
import ar.com.larctest.providers.HorsesProvider;
import ar.com.larctest.providers.HorsesRacingProvider;
import ar.com.larctest.utils.AppGlobalVariables;
import ar.com.larctest.utils.Constants;
import ar.com.larctest.utils.CustomHttpClient;
import ar.com.larctest.utils.MCrypt;

public class UpdateHorses extends AsyncTask<Void, Integer, Void> {
	private static final String TAG = "UpdateTypeWaysTask";

	private Activity activity;
    ProgressDialog dialog;
	Handler handlerActivity;

	public UpdateHorses(Activity activity, Handler handlerActivity) {
		this.activity = activity;
		this.handlerActivity = handlerActivity;
	}
		
	@Override
	protected Void doInBackground(Void... arg0) {
		doUpdate();
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		if (dialog != null && dialog.isShowing())
			dialog.dismiss();

        handlerActivity.sendEmptyMessage(Constants.TASK_SYNC_HORSES);
    }

	@Override
	protected void onPreExecute() {
		dialog = new ProgressDialog(activity);
		dialog.setMessage(activity.getText(R.string.updateHorses));
		dialog.setTitle(activity.getText(R.string.app_name));        
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);        
		dialog.setCancelable(false);
		dialog.show();
	}

	public void doUpdate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat(Constants.FORMAT_DATE_MYSQL);

        SQLLARCTESTHelper sqlHelper = SQLLARCTESTHelper.getHelper(activity);
		sqlHelper.dbOpen();

		try 
		{
			HorsesProvider horsesProvider = new HorsesProvider(activity);
            HorsesRacingProvider horsesRacingProvider = new HorsesRacingProvider(activity);
			sqlHelper.beginTransaction();

            ArrayList<NameValuePair> postParameters;
            String response;

            MCrypt encryptAES = new MCrypt();

            //Horse Sync
            postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_GETHORSES));
            postParameters.add(new BasicNameValuePair(Constants.PARAM_IDUSER, AppGlobalVariables.getInstance().getIdUser().toString()));

            response = CustomHttpClient.executeHttpPost(Constants.URL, postParameters);

            JSONArray jaHorses = new JSONArray(response);

            dialog.setProgress(0);
            dialog.setMax(jaHorses.length());
				
            for(int iLoop = 0; iLoop<jaHorses.length(); iLoop++){
                JSONObject joHorse = (JSONObject) jaHorses.get(iLoop);

                Horses horse = new Horses();
                horse.setName(new String(encryptAES.decrypt(joHorse.getString("name"))));
                horse.setYearsOld(Integer.parseInt(new String(encryptAES.decrypt(joHorse.getString("yearsOld")))));
                horse.setHair(new String(encryptAES.decrypt(joHorse.getString("hair"))));
                horse.setTemperament(new String(encryptAES.decrypt(joHorse.getString("temperament"))));
                horse.setState(joHorse.getString("state"));
                horse.setIdUser(joHorse.getInt("idUser"));
                horse.setIdHorseWeb(joHorse.getInt("idHorse"));
                horse.setRacings(new ArrayList<HorsesRacing>());

                JSONArray jaRacing = new JSONArray(joHorse.getString("racing"));

                horsesRacingProvider.removeRacingsHorse(horse.getIdHorse());
                for(int jLoop = 0; jLoop<jaRacing.length(); jLoop++){
                    JSONObject joRace = (JSONObject) jaRacing.get(jLoop);

                    HorsesRacing horsesRacing = new HorsesRacing();
                    horsesRacing.setIdHorseRacing(joRace.getInt("idHorseRacing"));
                    horsesRacing.setIdHorse(horse.getIdHorse());
                    horsesRacing.setDateRacing(sdf.parse(new String(encryptAES.decrypt(joRace.getString("dateRacing")))));
                    horsesRacing.setDistance(Double.parseDouble(new String(encryptAES.decrypt(joRace.getString("distance")))));

                    horsesRacingProvider.insertHorsesRacings(horsesRacing);

                    horse.getRacings().add(horsesRacing);
                }

                horsesProvider.insertOrUpdateHorse(horse);

                publishProgress(iLoop);
            }

            sqlHelper.commitTransaction();

            //Sync Horses without Sync
            List<Horses> horses = horsesProvider.getHorses();

            jaHorses = new JSONArray();
            for(Horses horse:horses) {
                if(horse.getState().equals(Constants.NOT_SYNC_RECORD)) {
                    JSONObject joHorse = new JSONObject();

                    joHorse.accumulate("idHorse", horse.getIdHorse());
                    joHorse.accumulate("name", encryptAES.encrypt(horse.getName()));
                    joHorse.accumulate("yearsOld", encryptAES.encrypt(horse.getYearsOld().toString()));
                    joHorse.accumulate("hair", encryptAES.encrypt(horse.getHair()));
                    joHorse.accumulate("temperament", encryptAES.encrypt(horse.getTemperament()));
                    joHorse.accumulate("idUser", horse.getIdUser());

                    jaHorses.put(joHorse);
                }
            }

            postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_SETHORSES));
            postParameters.add(new BasicNameValuePair("jaHorses", jaHorses.toString()));

            response = CustomHttpClient.executeHttpPost(Constants.URL, postParameters);

            JSONObject jsonResponse = new JSONObject(response);

            if(jsonResponse.getString("status").equals("ERROR")) {
                Log.e(TAG, "ERROR SYNC HORSES." + jsonResponse.getString("msg"));
            }
            else {
                JSONArray jaHorsesIds = new JSONArray(jsonResponse.getString("data"));
                for(int jLoop = 0; jLoop<jaHorsesIds.length(); jLoop++){
                    JSONObject joIds = (JSONObject) jaHorsesIds.get(jLoop);

                    horsesProvider.updateHorsesIdWeb(joIds.getInt("idHorse"), joIds.getInt("idWeb"));
                }
            }

		} catch (Exception e) {
			sqlHelper.rollbackTransaction();
			Log.e(TAG, "ERROR SYNC HORSES." + e);
		}
		finally {
			sqlHelper.dbClose();
		}
	}
	
	protected void onProgressUpdate (Integer... progress) {
        dialog.setProgress(progress[0]);
    }
}
